void solve()
{
  int n;
  cin >> n;

  vvi g(n + 1);
  rep(i, 1, n) {
    int fa;
    cin >> fa;
    g[fa].pb(i);  
  }

  vi son(n + 1), siz(n + 1), L(n + 1), R(n + 1), V(n + 2), dep(n + 1);
  vvi f(n + 1, vi(20, 0));
  int tim = 0;
  auto dfs = [&](auto &&dfs, int u, int p = 0) -> void {
    siz[u] = 1;
    f[u][0] = p;
    L[u] = ++tim;
    V[tim] = u;
    dep[u] = dep[p] + 1;
    for (auto &v : g[u]) {
      if (!L[v]) {
        dfs(dfs, v, u);
        siz[u] += siz[v];
        if (!son[u] || (siz[v] > siz[son[u]])) {
          son[u] = v;
        }
      }
    }
    R[u] = tim;
  };
  dfs(dfs, 0);
  for (int i = 1; i <= 19; i++) {
    for (int j = 0; j <= n; j++) {
      f[j][i] = f[f[j][i - 1]][i - 1];
    }
  }

  auto get_fak = [&](int v, int k) {
    for (int j = 19; j >= 0; j--) {
      if (k >> j & 1) {
        v = f[v][j];
      }
      if (!v) {
        break;
      }
    }
    return v;
  };
  
  vector<vector<pii>> query(n + 1);
  int m;
  cin >> m;

  rep(i, 1, m) {
    int u, k;
    cin >> u >> k;
    u = get_fak(u, k);
    if (u) {
      query[u].pb({k, i});
    }
  }

  vi cnt(n + 2), ans(m + 1);
  auto add = [&](int u) {
    cnt[dep[u]]++;
  };

  auto del = [&](int u) {
    cnt[dep[u]]--;
  };
  
  auto dfs2 = [&](auto &&dfs2, int u, int p, bool keep) -> void {
    for (auto &v : g[u]) {
      if (v != p && v != son[u]) {
        dfs2(dfs2, v, u, false);
      }
    }
    if (son[u]) {
      dfs2(dfs2, son[u], u, true);
    }
    for (auto &v : g[u]) {
      if (v != p && v != son[u]) {
        for (int i = L[v]; i <= R[v]; i++) {
          add(V[i]);
        }
      }
    }
    add(u);
    for (auto &[k, id] : query[u]) {
      ans[id] = cnt[dep[u] + k] - 1;
    }
    if (!keep) {
      for (int i = L[u]; i <= R[u]; i++) {
        del(V[i]);
      }
    }
  };
  dfs2(dfs2, 0, 0, false);
  rep(i, 1, m) {
    cout << ans[i] << ' ';
  }
  cout << '\n';
}